/**
 * tag
 * @authors 杨兴洲（of2502）
 * @date    2017/5/3 0003 10:21
 * @version 1.0
 */

import {Router} from "express";
import UserService from "../../service/user-service";
import WxUserService from "../../service/weixin-user-service";

const router = Router();
export default router;

/**
 * 获取标签列表
 */
router.get('/list', (req, res, next) => {
    (async () => {
        try {
            const {userID} = res.locals;
            let access_token = await UserService.getAccessToken(userID);
            let result: any = await WxUserService.getTags(access_token);
            res.status(200).json(result);
        } catch (error) {
            next(error);
        }
    })();
});

/**
 * 新建标签
 */
router.post('/create', (req, res, next) => {
    (async () => {
        try {
            const {userID} = res.locals;
            const {tagName} = req.body;
            let access_token = await UserService.getAccessToken(userID);
            let result: any = await WxUserService.createTag({access_token, tagName});
            res.status(200).json(result);
        } catch (error) {
            next(error);
        }
    })();
});

/**
 * 更新标签
 */
router.post('/update', (req, res, next) => {
    (async () => {
        try {
            const {userID} = res.locals;
            const {tagID, tagName} = req.body;
            if (!tagID || !tagName) {
                const error = new Error();
                error["errcode"] = 10001;
                error["errmsg"] = "tagID或者tagName不能为空";
                return next(error);
            }
            let access_token = await UserService.getAccessToken(userID);
            let result: any = await WxUserService.updateTag({access_token, tagID, tagName});
            res.status(200).json(result);
        } catch (error) {
            next(error);
        }
    })();
});

/**
 * 删除标签
 */
router.post('/delete', (req, res, next) => {
    (async () => {
        try {
            const {userID} = res.locals;
            const {tagID} = req.body;
            if (!tagID) {
                const error = new Error();
                error["errcode"] = 10001;
                error["errmsg"] = "tagID不能为空";
                return next(error);
            }
            let access_token = await UserService.getAccessToken(userID);
            let result: any = await WxUserService.deleteTag({access_token, tagID});
            res.status(200).json(result);
        } catch (error) {
            next(error);
        }
    })();
});
